package com.md.livingwidget.dialog;

import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Point;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.text.InputType;
import android.text.method.LinkMovementMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ScrollView;

import com.md.basedpc.PHSizeUtils;
import com.md.basedpc.PHUtils;
import com.md.livingwidget.R;
import com.md.livingwidget.dialog.internal.DLAdapter;
import com.md.livingwidget.dialog.internal.DLButton;
import com.md.livingwidget.dialog.internal.DLRootLayout;
import com.md.livingwidget.dialog.internal.DLTintHelper;
import com.md.livingwidget.dialog.util.DialogUtils;
import com.md.livingwidget.uiutils.ShapeUtils;

import java.util.ArrayList;
import java.util.Arrays;
import androidx.annotation.LayoutRes;
import androidx.annotation.UiThread;
/**
 * 弹框UI初始化
 *
 * @author wanggq
 * @date :2019-11-25 17:46
 */
public class DialogInit {

    @LayoutRes
    static int getInflateLayout(MaterialDialog.Builder builder) {
        if (builder.customView != null) {
            return R.layout.ph_dialog_custom;
        } else if (builder.items != null || builder.adapter != null) {
            if (builder.checkBoxPrompt != null) {
                return R.layout.ph_dialog_list_check;
            }
            return R.layout.ph_dialog_list;
        } else if (builder.inputCallback != null) {
            if (builder.checkBoxPrompt != null) {
                return R.layout.ph_dialog_input_check;
            }
            return R.layout.ph_dialog_input;
        } else if (builder.checkBoxPrompt != null) {
            return R.layout.ph_dialog_basic_check;
        } else {
            return R.layout.ph_dialog_basic;
        }
    }

    @SuppressWarnings("ConstantConditions")
    @UiThread
    static void init(final MaterialDialog dialog) {
        final MaterialDialog.Builder builder = dialog.builder;
        // Set cancelable flag and dialog background color
        dialog.setCancelable(builder.cancelable);
        dialog.setCanceledOnTouchOutside(builder.canceledOnTouchOutside);
//        if (builder.backgroundColor == -1) {
//            builder.backgroundColor = builder.context.getResources().getColor(R.color.ui_dialog_bg);
//        }
        GradientDrawable drawable = new GradientDrawable();
        drawable.setCornerRadius(dialog.builder.context.getResources().getDimension(R.dimen.md_bg_corner_radius));
//        drawable.setColor(builder.backgroundColor);
        drawable.setColor(builder.context.getResources().getColor(R.color.ui_dialog_bg));
        dialog.view.setBackgroundDrawable(drawable);

        GradientDrawable drawable11 = new GradientDrawable();
        drawable11.setColor(builder.context.getResources().getColor(R.color.ui_dialog_bg_transparent));
        dialog.getWindow().setBackgroundDrawable(drawable11);


        int colol = builder.context.getResources().getColor(R.color.ui_dialog_title);
        ColorStateList defaultColor = ShapeUtils.getColorStateList(colol, colol, colol);
        // Retrieve color theme attributes
        if (!builder.positiveColorSet) {
            builder.positiveColor = defaultColor;
        }
        if (!builder.neutralColorSet) {
            builder.neutralColor = defaultColor;
        }
        if (!builder.negativeColorSet) {
            builder.negativeColor = defaultColor;
        }
        // Retrieve default title/content colors
        if (!builder.titleColorSet) {
            builder.titleColor = builder.context.getResources().getColor(R.color.ui_dialog_title);
        }
        if (!builder.contentColorSet) {
            builder.contentColor = builder.context.getResources().getColor(R.color.ui_dialog_content);
        }
        if (!builder.itemColorSet) {
            builder.itemColor = builder.context.getResources().getColor(R.color.ui_dialog_title);
        }
        dialog.icon0 = dialog.rootView.findViewById(R.id.md_icon0);
        // Retrieve references to views
        dialog.title = dialog.view.findViewById(R.id.md_title);
        dialog.icon = dialog.view.findViewById(R.id.md_icon);
        dialog.titleFrame = dialog.view.findViewById(R.id.md_titleFrame);
        dialog.contentScrollView = dialog.view.findViewById(R.id.md_contentScrollView);
        dialog.content = dialog.view.findViewById(R.id.md_content);
        dialog.recyclerView = dialog.view.findViewById(R.id.md_contentRecyclerView);
        dialog.checkBoxPrompt = dialog.view.findViewById(R.id.md_promptCheckbox);
        // Button views initially used by checkIfStackingNeeded()
        dialog.positiveButton = dialog.view.findViewById(R.id.md_buttonDefaultPositive);
        dialog.neutralButton = dialog.view.findViewById(R.id.md_buttonDefaultNeutral);
        dialog.negativeButton = dialog.view.findViewById(R.id.md_buttonDefaultNegative);
        // Don't allow the submit button to not be shown for input dialogs
        if (builder.inputCallback != null && builder.positiveText == null) {
            builder.positiveText = builder.context.getText(android.R.string.ok);
        }
        // Set up the initial visibility of action buttons based on whether or not text was set
        dialog.positiveButton.setVisibility(builder.positiveText != null ? View.VISIBLE : View.GONE);
        dialog.neutralButton.setVisibility(builder.neutralText != null ? View.VISIBLE : View.GONE);
        dialog.negativeButton.setVisibility(builder.negativeText != null ? View.VISIBLE : View.GONE);

        // Set up the focus of action buttons
        dialog.positiveButton.setFocusable(true);
        dialog.neutralButton.setFocusable(true);
        dialog.negativeButton.setFocusable(true);
        if (builder.positiveFocus) {
            dialog.positiveButton.requestFocus();
        }
        if (builder.neutralFocus) {
            dialog.neutralButton.requestFocus();
        }
        if (builder.negativeFocus) {
            dialog.negativeButton.requestFocus();
        }
        // Setup icon
        if (builder.icon != null) {
            dialog.icon0.setVisibility(View.VISIBLE);
            dialog.icon0.setImageDrawable(builder.icon);
        }
        // Setup icon size limiting
        int maxIconSize = builder.maxIconSize;
        if (maxIconSize > -1) {
            dialog.icon0.setScaleType(ImageView.ScaleType.FIT_XY);
            dialog.icon0.setMaxHeight(maxIconSize);
            dialog.icon0.getLayoutParams().height = maxIconSize;
//            dialog.icon.setMaxWidth(maxIconSize);
            dialog.icon0.requestLayout();
            int topImageviewHeight = maxIconSize;
//            float rediss = PHSizeUtils.dp2px(dialog.builder.context, 5);
            float rediss = dialog.builder.context.getResources().getDimension(R.dimen.md_bg_corner_radius);
            dialog.view.setTopImageHeight(topImageviewHeight - (int) (1f * rediss));
        }

        // Setup divider color in case content scrolls
        if (!builder.dividerColorSet) {
            builder.dividerColor = dialog.getContext().getResources().getColor(R.color.ui_dialog_btn_divider);
        }
        dialog.view.setDividerColor(builder.dividerColor);

        // Setup title and title frame
        if (dialog.title != null) {
            dialog.setTypeface(dialog.title, builder.mediumFont);
            dialog.title.setTextColor(builder.titleColor);
            dialog.title.setGravity(builder.titleGravity.getGravityInt());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                //noinspection ResourceType
                dialog.title.setTextAlignment(builder.titleGravity.getTextAlignment());
            }
            if (builder.title == null) {
                dialog.titleFrame.setVisibility(View.GONE);
            } else {
                dialog.title.setText(builder.title);
                if (!PHUtils.isEmpty(builder.title))
                    dialog.titleFrame.setVisibility(View.VISIBLE);
                else
                    dialog.titleFrame.setVisibility(View.GONE);
            }
            dialog.title.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                @Override
                public boolean onPreDraw() {
                    int line = dialog.title.getLineCount();
                    if (line > 2) {
                        dialog.title.setTextAlignment(GravityEnum.START.getTextAlignment());
                        dialog.title.setGravity(Gravity.LEFT);
                    } else {
                        dialog.title.setTextAlignment(GravityEnum.CENTER.getTextAlignment());
                        dialog.title.setGravity(Gravity.CENTER);
                    }
                    return true;
                }
            });
        }

        if (dialog.contentScrollView != null) {
            dialog.contentScrollView.setMaxHeight(builder.contentMaxHeight);
        }
        // Setup content
        if (dialog.content != null) {
            dialog.content.setMovementMethod(new LinkMovementMethod());
            dialog.setTypeface(dialog.content, builder.regularFont);
            dialog.content.setLineSpacing(0f, builder.contentLineSpacingMultiplier);
            if (builder.linkColor == null) {
                dialog.content.setLinkTextColor(
                        DialogUtils.resolveColor(dialog.getContext(), android.R.attr.textColorPrimary));
            } else {
                dialog.content.setLinkTextColor(builder.linkColor);
            }
            dialog.content.setTextColor(builder.contentColor);
            dialog.content.setGravity(builder.contentGravity.getGravityInt());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                //noinspection ResourceType
                dialog.content.setTextAlignment(builder.contentGravity.getTextAlignment());
            }

            if (builder.content != null) {
                dialog.content.setText(builder.content);
                if (!PHUtils.isEmpty(builder.content))
                    dialog.content.setVisibility(View.VISIBLE);
                else {
                    dialog.content.setVisibility(View.GONE);
                }
            } else {
                dialog.content.setVisibility(View.GONE);
            }
            dialog.content.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                @Override
                public boolean onPreDraw() {
                    int line = dialog.content.getLineCount();
                    if (line > 2) {
                        dialog.content.setTextAlignment(GravityEnum.START.getTextAlignment());
                        dialog.content.setGravity(Gravity.LEFT);
                    } else {
                        dialog.content.setTextAlignment(GravityEnum.CENTER.getTextAlignment());
                        dialog.content.setGravity(Gravity.CENTER);
                    }
                    return true;
                }
            });
        }

        // Setup prompt checkbox
        if (dialog.checkBoxPrompt != null) {
            dialog.checkBoxPrompt.setText(builder.checkBoxPrompt);
            dialog.checkBoxPrompt.setChecked(builder.checkBoxPromptInitiallyChecked);
            dialog.checkBoxPrompt.setOnCheckedChangeListener(builder.checkBoxPromptListener);
            dialog.setTypeface(dialog.checkBoxPrompt, builder.regularFont);
            dialog.checkBoxPrompt.setTextColor(builder.contentColor);
            DLTintHelper.setTint(dialog.checkBoxPrompt, builder.widgetColor);
        }

        // Setup action buttons
        dialog.view.setButtonBgColor(builder.backgroundColor);
        dialog.view.setButtonGravity(builder.buttonsGravity);
        dialog.view.setButtonStackedGravity(builder.btnStackedGravity);
        dialog.view.setStackingBehavior(builder.stackingBehavior);
        boolean textAllCaps = false;
        DLButton positiveTextView = dialog.positiveButton;
//        dialog.setTypeface(positiveTextView, builder.mediumFont);
        positiveTextView.setAllCapsCompat(textAllCaps);
        positiveTextView.setText(builder.positiveText);
        positiveTextView.setTextColor(builder.positiveColor);
        dialog.positiveButton.setStackedSelector(dialog.getButtonSelector(DialogAction.POSITIVE, true));
        dialog.positiveButton.setDefaultSelector(dialog.getButtonSelector(DialogAction.POSITIVE, false));
        dialog.positiveButton.setTag(DialogAction.POSITIVE);
        dialog.positiveButton.setOnClickListener(dialog);

        DLButton negativeTextView = dialog.negativeButton;
//        dialog.setTypeface(negativeTextView, builder.mediumFont);
        negativeTextView.setAllCapsCompat(textAllCaps);
        negativeTextView.setText(builder.negativeText);
        negativeTextView.setTextColor(builder.negativeColor);
        dialog.negativeButton.setStackedSelector(dialog.getButtonSelector(DialogAction.NEGATIVE, true));
        dialog.negativeButton.setDefaultSelector(dialog.getButtonSelector(DialogAction.NEGATIVE, false));
        dialog.negativeButton.setTag(DialogAction.NEGATIVE);
        dialog.negativeButton.setOnClickListener(dialog);

        DLButton neutralTextView = dialog.neutralButton;
//        dialog.setTypeface(neutralTextView, builder.mediumFont);
        neutralTextView.setAllCapsCompat(textAllCaps);
        neutralTextView.setText(builder.neutralText);
        neutralTextView.setTextColor(builder.neutralColor);
        dialog.neutralButton.setStackedSelector(dialog.getButtonSelector(DialogAction.NEUTRAL, true));
        dialog.neutralButton.setDefaultSelector(dialog.getButtonSelector(DialogAction.NEUTRAL, false));
        dialog.neutralButton.setTag(DialogAction.NEUTRAL);
        dialog.neutralButton.setOnClickListener(dialog);

        // Setup list dialog stuff
        if (builder.listCallbackMultiChoice != null) {
            dialog.selectedIndicesList = new ArrayList<>();
        }
        if (dialog.recyclerView != null) {
            if (builder.adapter == null) {
                // Determine list type
                if (builder.listCallbackSingleChoice != null) {
                    dialog.listType = MaterialDialog.ListType.SINGLE;
                } else if (builder.listCallbackMultiChoice != null) {
                    dialog.listType = MaterialDialog.ListType.MULTI;
                    if (builder.selectedIndices != null) {
                        dialog.selectedIndicesList = new ArrayList<>(Arrays.asList(builder.selectedIndices));
                        builder.selectedIndices = null;
                    }
                } else {
                    dialog.listType = MaterialDialog.ListType.REGULAR;
                }
                builder.adapter = new DefaultRvAdapter(dialog, MaterialDialog.ListType.getLayoutForType(dialog.listType));
            } else if (builder.adapter instanceof DLAdapter) {
                // Notify simple list adapter of the dialog it belongs to
                ((DLAdapter) builder.adapter).setDialog(dialog);
            }
        }

        // Setup input dialog stuff if needed
        setupInputDialog(dialog);

        // Setup custom views
        if (builder.customView != null) {
            ((DLRootLayout) dialog.view.findViewById(R.id.md_root)).noTitleNoPadding();
            FrameLayout frame = dialog.view.findViewById(R.id.md_customViewFrame);
            dialog.customViewFrame = frame;
            View innerView = builder.customView;
            if (innerView.getParent() != null) {
                ((ViewGroup) innerView.getParent()).removeView(innerView);
            }
            if (builder.wrapCustomViewInScroll) {
              /* Apply the frame padding to the content, this allows the ScrollView to draw it's
                 over scroll glow without clipping */
                final Resources r = dialog.getContext().getResources();
                final ScrollView sv = new ScrollView(dialog.getContext());
                final int framePadding = PHSizeUtils.dp2px(dialog.builder.context, 24);
                int paddingTop = PHSizeUtils.dp2px(dialog.builder.context, 4);
                int paddingBottom = PHSizeUtils.dp2px(dialog.builder.context, 4);
                sv.setClipToPadding(false);
                if (innerView instanceof EditText) {
                    // Setting padding to an EditText causes visual errors, set it to the parent instead
                    sv.setPadding(framePadding, paddingTop, framePadding, paddingBottom);
                } else {
                    // Setting padding to scroll view pushes the scroll bars out, don't do it if not necessary
                    sv.setPadding(0, paddingTop, 0, paddingBottom);
                    innerView.setPadding(framePadding, 0, framePadding, 0);
                }
                sv.addView(innerView, new ScrollView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                innerView = sv;
            }
            frame.addView(innerView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        }

        // Setup user listeners
        if (builder.showListener != null) {
            dialog.setOnShowListener(builder.showListener);
        }
        if (builder.cancelListener != null) {
            dialog.setOnCancelListener(builder.cancelListener);
        }
        if (builder.dismissListener != null) {
            dialog.setOnDismissListener(builder.dismissListener);
        }
        if (builder.keyListener != null) {
            dialog.setOnKeyListener(builder.keyListener);
        }

        // Setup internal show listener
        dialog.setOnShowListenerInternal();

        // Other internal initialization
        dialog.invalidateList();
//        dialog.setViewInternal(dialog.view);
        dialog.setViewInternal(dialog.rootView);

        dialog.checkIfListInitScroll();

        // Min height and max width calculations
        WindowManager wm = dialog.getWindow().getWindowManager();
        Display display = wm.getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        final int windowWidth = size.x;
        final int windowHeight = size.y;

        final int windowVerticalPadding = PHSizeUtils.dp2px(dialog.builder.context, 52);
        final int maxWidth = PHSizeUtils.dp2px(dialog.builder.context, 320);
        final int calculatedWidth = windowWidth * 3 / 4;

        dialog.view.setMaxHeight(windowHeight - windowVerticalPadding * 2);
//        dialog.view.setMaxHeight(windowHeight * 3 / 5 - windowVerticalPadding * 2);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(dialog.getWindow().getAttributes());
        lp.width = Math.min(maxWidth, calculatedWidth);
        dialog.getWindow().setAttributes(lp);
    }

    /**
     * 输入框初始化
     *
     * @param dialog
     */
    private static void setupInputDialog(final MaterialDialog dialog) {
        final MaterialDialog.Builder builder = dialog.builder;
        dialog.input = dialog.view.findViewById(android.R.id.input);
        dialog.input_layout = dialog.view.findViewById(R.id.input_layout);
        if (dialog.input == null) {
            return;
        }
        dialog.setTypeface(dialog.input, builder.regularFont);
        if (builder.inputPrefill != null) {
            dialog.input.setText(builder.inputPrefill);
        }
        dialog.setInternalInputCallback();
        dialog.input.setHint(builder.inputHint);
//        dialog.input.setSingleLine();
        dialog.input.setMinHeight(builder.contentMaxHeight);
        dialog.input.getLayoutParams().height = builder.contentMaxHeight;
        dialog.input.setTextColor(builder.contentColor);
        dialog.input.setBackgroundColor(dialog.getContext().getResources().getColor(R.color.transparent));
//        dialog.input.setHintTextColor(DialogUtils.adjustAlpha(builder.contentColor, 0.3f));
//        MDTintHelper.setTint(dialog.input, dialog.builder.widgetColor);
        dialog.input.setBackground(ShapeUtils.getDrawableList(1, 5, dialog.getContext().getResources().getColor(R.color.ui_dialog_input_stroke), dialog.getContext().getResources().getColor(R.color.ui_dialog_bg_transparent)));
        if (builder.inputType != -1) {
            dialog.input.setInputType(builder.inputType);
            if (builder.inputType != InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD && (builder.inputType & InputType.TYPE_TEXT_VARIATION_PASSWORD) == InputType.TYPE_TEXT_VARIATION_PASSWORD) {
                // If the flags contain TYPE_TEXT_VARIATION_PASSWORD, apply the password transformation
                // method automatically
                dialog.input.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }
        }
        dialog.inputMinMax = dialog.view.findViewById(R.id.md_minMax);
        if (builder.inputMinLength > 0 || builder.inputMaxLength > -1) {
            dialog.invalidateInputMinMaxIndicator(dialog.input.getText().toString().length(), !builder.inputAllowEmpty);
        } else {
            dialog.inputMinMax.setVisibility(View.GONE);
            dialog.inputMinMax = null;
        }
        if (builder.inputFilters != null) {
            dialog.input.setFilters(builder.inputFilters);
        }

    }


}
